#include <iostream>
#include <cstdio>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
using namespace std;

class File
{
public:
    File(const char *filepath) : filepath(filepath)
    {
        fp = fopen(filepath, "w+");
        if (fp == NULL)
        {
            perror("fopen");
            exit(1);
        }
        cout << "open success" << endl;
    }

    void write(const char *str);
    void read(char *buf);

    ~File()
    {
        fclose(fp);
        cout << "close success" << endl;
    }

private:
    FILE *fp;
    const char *filepath;
};

void File::write(const char *str)
{
    fwrite(str, strlen(str), 1, fp);
}

void File::read(char *buf)
{

    fseek(fp, 0, SEEK_SET); // 将文件指针移动到文件开头
    fread(buf, 1, 1024 - 1, fp);
    buf[strlen(buf)] = '\0';
}

int main()
{
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    File *f1 = new File("./test.txt");
    f1->write("hello world");
    f1->read(buf);
    cout << buf << endl;

    delete f1;
}